<?php

namespace App\Ad\Docking;

use App\Ad\MediaApi\MediaApiBase;
use App\Commons\CommonConstant;
use App\Datalog\AdMonitorLog;
use App\Models\AdMonitor;
use App\Models\AdPlan;
use App\Models\FirstupAd;
use App\Models\Log\LogAdMonitor;
use App\Models\Log\LogAdMonitorInfo;
use App\Models\Log\LogAdPostbackMedia;
use Illuminate\Http\Request;

// Bilibili-微信小程序
// 对接文档
// https://docs.qq.com/doc/DRmVwVnd1RllYS0Fo
// https://docs.qq.com/doc/DV25tS0dldlpCc3hX
class BilibiliXyx extends DockingBase
{
    // 点击监控参数
    protected $monitorParams = [
        'track_id'     => '__TRACKID__',       // 点击跟踪id 用于匹配归因
        'account_id'   => '__ACCOUNTID__',     // 广告主id
        'campaign_id'  => '__CAMPAIGNID__',    // 计划id
        'unit_id'      => '__UNITID__',        // 单元id
        'creative_id'  => '__CREATIVEID__',    // 创意id
        'os'           => '__OS__',            // 数字,取0~3。0表示Android，1表示iOS，2表示Windows Phone，3表示其他
        'imei'         => '__IMEI__',          // imei
        'callback_url' => '__CALLBACKURL__',   // 回调地址（需要urlencode）
        'mac1'         => '__MAC1__',          // 用户终端的eth0 接口的 MAC 地址
        'idfa_md5'     => '__IDFAMD5__',       // idfa
        'caid'         => '__CAID__',          // caid
        'aaid'         => '__AAID__',          // Android Advertising ID
        'android_id'   => '__ANDROIDID__',     // android_id
        'oaid_md5'     => '__OAIDMD5__',       // oaid
        'ip'           => '__IP__',            // ip
        'ua'           => '__UA__',            // user agent
        'model'        => '__MODEL__',         // 手机型号
        'ts'           => '__TS__',            // 客户端触发监测的时间 UTC时间戳
        'shop_id'      => '__SHOPID__',        // 店铺ID
        'upm_id'       => '__UPMID__',         // 视频UP主MID
    ];

    // 转化类型映射
    protected $eventTypeMap = [
        CommonConstant::EVENT_REG => 'FORM_SUBMIT',
        CommonConstant::EVENT_PAY => 'USER_COST',
    ];

    // 此接口由子类继承
    // 获得点击监控链接拼接参数
    public function getMonitorParams($device_type): string
    {
        return http_build_query($this->monitorParams);
    }

    // 此接口由子类继承
    // 处理落地监控数据
    public function handleMonitorInfo(Request $request)
    {
        // 待匹配日志
        $params           = $request->all();
        $log              = LogAdMonitor::suffix(date('Ym'));
        $log->create_time = time();
        $log->plan_id     = $params['plan_id'];
        $log->ip          = $params['ip'] ?? '';
        $log->click_id    = $params['track_id'];
        $log->save();

        // 完整日志
        $info              = LogAdMonitorInfo::suffix(date('Ym'));
        $info->create_time = time();
        $info->plan_id     = $params['plan_id'];
        $info->monitor_id  = $log->id;
        $info->data        = json_encode($params, JSON_UNESCAPED_UNICODE);
        $info->save();

        // 落地日志
        AdMonitorLog::getInstance()->addLog($log, $info);

        return yqok();
    }

    /**
     * 此接口由子类继承
     * 根据媒体加密方式-生成对应的设备码，用于匹配
     * @param int      $device_type 设备类型
     * @param string[] $device_nums 设备码
     * @return array
     */
    public function getMonitorDeviceNum($device_type, $device_nums): array
    {
        $data = [];
        foreach ($device_nums as $key => $val) {
            switch ($key) {
                case 'click_id':
                    $data[$key] = $val;
                    break;
            }
        }

        return $data;
    }

    /**
     * 此接口由子类继承
     * 将用户行为进行api上报转化，如激活注册付费
     *
     * @param int $event_type 事件类型 如激活注册付费
     * @param AdMonitor $monitor
     * @param FirstupAd $firstup_ad
     * @param mixed $mod 事件对应的模型 激活 Firstup 注册 Users 付费 Orders
     * @return int 处理结果状态
     */
    public function postbackToMedia($event_type, AdMonitor $monitor, FirstupAd $firstup_ad, $mod): int
    {
        // 此事件不需要上报
        if (!isset($this->eventTypeMap[$event_type])) {
            return LogAdPostbackMedia::STATUS_NONEED;
        }

        $plan = AdPlan::find($firstup_ad->plan_id);

        // 如果非API自上报则无需处理
        if ($plan['access_type'] != AdPlan::ACCESS_TYPE_API) {
            return LogAdPostbackMedia::STATUS_NOTAPI;
        }

        $monitor_data = json_decode($monitor->data, true);

        $params = [
            'conv_type' => $this->eventTypeMap[$event_type],
            'conv_time' => $mod->create_time,
            'track_id' => $monitor_data['track_id'],
        ];

        // 如果是充值加传金额
        $is_pay = $event_type == CommonConstant::EVENT_PAY;
        if ($is_pay) {
            $params['conv_value'] = $mod->call_money * 100;
        }

        // 不存在callback
        if (!isset($monitor_data['callback_url'])) {
            return LogAdPostbackMedia::STATUS_NOCALLBACK;
        }

        $url = 'https://cm.bilibili.com/conv/api/conversion/ad/cb/v1';
        $res  = MediaApiBase::getInstance()->curl($url, $params, false, true);

        if ($res[0] != 200) {
            return LogAdPostbackMedia::STATUS_FAIL;
        }

        return LogAdPostbackMedia::STATUS_SUCC;
    }

    // 此接口由子类继承
    // 匹配成功后补齐监控数据
    public function supplementMonitorInfo(FirstupAd $firstup_ad, AdMonitor $monitor)
    {
        $data = json_decode($monitor->data, true);

        $firstup_ad->advertiser_id = intval($data['account_id'] ?? 0);   // 广告主id
        $firstup_ad->campaign_id   = intval($data['campaign_id'] ?? 0);  // 计划id
        $firstup_ad->ad_id         = intval($data['unit_id'] ?? 0);      // 单元id
        $firstup_ad->creative_id   = intval($data['creative_id'] ?? 0);  // 创意id
    }
}
